package com.common.util.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.facade.MembershipFacade;
import com.model.Membership;


@FacesValidator("MembershipNameValidator")
public class MembershipNameValidator implements Validator{
	
	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		
		Membership preloadMembership = (Membership)FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("validatorMembershipUpdate");
		
		MembershipFacade membershipFacade = new MembershipFacade();
		Membership membership = membershipFacade.findMemberWithName(value.toString());
		
		if(preloadMembership != null && membership != null && preloadMembership.getName().equals(value)){
			membership = null;
		}
		
		
		if(membership != null){
			FacesMessage msg = new FacesMessage("Membership Name. Validation Failed.", "Membership name already exist");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
	}
	
	
}
